<template>
  <div style="height:470px;">
      <table>
          <tr>
              <td>
                  <el-select v-model="modelcode" placeholder="" @change="modChange($event)" clearable filterable style="width:150px;">
                      <el-option v-for="(item,index) in modelOption" :key="index" :value="item.modelcode" :label="item.modelname"></el-option>
                  </el-select>
              </td>
              <td colspan="2">
                  <el-button @click="ModifyModel">修改模板</el-button>
                  <el-button @click="AddModel">新增模板</el-button>
                  <el-button @click="DelModel">删除模板</el-button>
              </td>
          </tr>
          <tr>
              <td colspan="3">
                  <div class="excol-content">
                      <div class="col-table">
                          <vxe-table ref="xColTable" :data.sync="exportColTableData" height="auto" width="100%" border size="mini" 
                              show-overflow show-header-overflow highlight-current-row resizable stripe header-align="center">
                              <vxe-table-column field="title" title="列名" width="170"></vxe-table-column>
                              <vxe-table-column field="extitle" title="导出列名" width="170"></vxe-table-column>
                          </vxe-table>
                      </div>
                  </div>
              </td>
          </tr>
          <tr>
              <td colspan="2" style="width:150px;">
                  <el-checkbox v-model="hidemodelflag" true-label="1" false-label="0" @change="hideModelChange()">隐藏该模板</el-checkbox>
                  <el-checkbox v-model="showallhidemodelflag" true-label="1" false-label="0" @change="ShowModelChange()">显示所有隐藏模板</el-checkbox>
              </td>
              <td>
                  <div class="excol-btn">
                      <el-button @click="dialogVisibleSave">确定使用</el-button>
                      <el-button @click="$emit('change')">取消</el-button>
                  </div>
              </td>
          </tr>
      </table>
      <el-dialog :title="modeltitle" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" :visible.sync="modelVisible" width="810px">
          <div style="height:500px;">
              <rm-layout-top splitcolor="white" :splitwidth=5 :fixsize=40 :canDrag="false">
                  <template v-slot:fix>
                      <table>
                          <tr>
                              <td>
                                  <el-input style="width:160px;" placeholder="请输入模板名称" v-model="modelinfo.modelname" ref="modelname"></el-input>
                              </td>
                              <td colspan="3">
                                  <el-checkbox v-model="overallModel" true-label="1" false-label="0">设置为全局模板</el-checkbox>
                              </td>
                          </tr>
                      </table>
                  </template>
                  <div class="excol-content">
                      <div class="col-table">
                          <vxe-table ref="ListxTableLeft" :data.sync="leftTableData" height="auto" width="100%" border size="mini" 
                              show-overflow show-header-overflow highlight-current-row resizable stripe header-align="center" 
                              :sort-config="{trigger: 'cell'}" @cell-dblclick="ListSelectEvent">
                              <vxe-table-column field="title" title="列名"  width="330" sortable></vxe-table-column>
                          </vxe-table>
                      </div>
                      <div class="col-arrow">
                          <div><el-button class="el-icon-right" @click="ListSelectEvent"></el-button></div>
                          <div><el-button class="el-icon-back" @click="ListNoSelectEvent"></el-button></div>
                          <div><el-button class="el-icon-d-arrow-right" @click="ListAllSelect"></el-button></div>
                          <div><el-button class="el-icon-d-arrow-left" @click="ListAllNoSelect"></el-button></div>
                      </div>
                      <div class="col-table">
                          <vxe-table ref="ListxTableRight" :data.sync="rightTableData" height="auto" width="100%" border size="mini" 
                              show-overflow show-header-overflow highlight-current-row resizable stripe header-align="center" 
                              @cell-dblclick="ListNoSelectEvent" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, showIcon: false }">
                              <vxe-table-column field="title" title="列名" width="170"></vxe-table-column>
                              <vxe-table-column field="extitle" title="导出列名" width="170" :edit-render="{name: 'input',autoselect:true}"></vxe-table-column>
                          </vxe-table>
                      </div>
                  </div>
                  <div class="excol-btn">
                      <el-button @click="SaveModel(1)">保存</el-button>
                      <el-button @click="CancelModel">取消</el-button>
                  </div>
              </rm-layout-top>
          </div>
      </el-dialog>
      <el-dialog title="提示" :visible.sync="deldialogVisible" v-if="deldialogVisible" v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" width="30%">
          <span><span class="el-icon-info">确定要删除名称为<b style="color: red">{{ message }}</b>的模板吗？</span></span>
          <span slot="footer" class="dialog-footer">
              <el-button @click="SubmitDel">确 定</el-button>
              <el-button @click="deldialogVisible = false">取 消</el-button>
          </span>
      </el-dialog>
  </div>
</template>

<script>
import XE from "xe-utils";
export default {
  name: "rm_excolsetting",
  props: {
      excolPro: {
          type: String,
          default: true,
      },
      allTableCol:{
          type: Array,
          default: true,
      },
  },
  data() {
      return {
          leftTableData: [],
          rightTableData: [],
          exportColTableData: [],
          modelOption: [],
          modelcode: "",
          modelinfo: {
              modelname: "",
          },
          changeflag: false,
          modeltitle: "",
          modelVisible: false,
          deldialogVisible: false,
          message: "",
          utype: "",//1:新增 2:更新 3:删除
          PRGNO: this.excolPro.toUpperCase(),
          hidemodelflag: "0",
          showallhidemodelflag: "0",
          overallModel: "0",
      }
  },
  created() {
      this.getOptions();
  },
  methods: {
      colSettingToDB() {
          console.log(this.excolPro + 'colSettingToDB');
          // 先找下老的本地缓存
          // LIS340之前有更老的缓存，防止不兼容，这里也存起来然后清本地缓存
          var lis340exportcol = JSON.parse(window.localStorage.getItem("exportColumn"));
          if (this.excolPro == "lis340" && lis340exportcol && lis340exportcol.length > 0){
              window.localStorage.setItem(this.excolPro + "exCol", JSON.stringify(lis340exportcol));
              window.localStorage.removeItem("noexportColumn");
              window.localStorage.removeItem("exportColumn");
          }
          var rightlocalStorage = JSON.parse(window.localStorage.getItem(this.excolPro + "exCol"));
          if(rightlocalStorage && rightlocalStorage.length > 0) {
              // 先取下导出列缓存
              this.utype = "1";
              this.modelinfo = {
                  modelname: this.excolPro.toUpperCase()+ "的默认模板",
                  columnlist: this.colListToStr(rightlocalStorage),
              };
              this.overallModel = "0";
              this.SaveModel(2).then(()=> {
                  // 把老的本地缓存都清了
                  window.localStorage.removeItem(this.excolPro + "noExCol");
                  window.localStorage.removeItem(this.excolPro + "exCol");
              });
          }
      },
      getOptions() {
          var usingmodel = window.localStorage.getItem(this.excolPro + "exportModel");
          this.$tool.request({
                  url: "ucent/exportcolsetting",
                  method: "post",
                  data: {
                      action: "getexportoptions",
                      prgcode: this.PRGNO,
                  },
              }).then((res)=>{
                  this.hidemodelflag = "0";
                  this.showallhidemodelflag = "0";
                  this.modelOption = res.modelOption;
                  if(this.modelOption && this.modelOption.length > 0) {
                      if(usingmodel) {
                          let model = this.modelOption.find((item) => item.modelcode == usingmodel);
                          if(model){
                              this.modelcode = model.modelcode;
                              this.exportColTableData = this.colStrToList(model.columnlist);
                          } else {
                              this.modelcode = this.modelOption[0].modelcode;
                              this.exportColTableData = this.colStrToList(this.modelOption[0].columnlist);
                          }
                      } else {
                          this.modelcode = this.modelOption[0].modelcode;
                          this.exportColTableData = this.colStrToList(this.modelOption[0].columnlist);
                      }
                  } else {
                      this.modelcode = "";
                      this.exportColTableData = [];
                  }
              }).catch((err)=>{
                  console.log(err);
              });
      },
      colStrToList(colstr) {
          let tabledata = [];
          if(colstr && colstr.length > 0) {
              var colsarr = colstr.split("|");
              colsarr.forEach((item) => {
                  let colarr = item.split(" ");
                  let property = colarr[0];
                  let title = colarr[1];
                  let extitle = "";
                  if(colarr[2] && colarr[2].length > 0) {
                      extitle = colarr[2];
                  }
                  if(property) {
                      var col = {
                          title: title,
                          extitle: extitle,
                          property: property,
                      };
                      tabledata.push(col);
                  }
              });
          }
          return tabledata;
      },
      colListToStr(tabledata) {
          let exportColumnStr = "";
          if (tabledata && tabledata.length > 0) {
              tabledata.forEach((item) => {
                  exportColumnStr += item.property + " " + item.title +  (item.extitle ? (" " +  item.extitle) : "") + "|";
              });
              if(exportColumnStr.length > 0) exportColumnStr = exportColumnStr.substring(0, exportColumnStr.length -1);
          }
          return exportColumnStr;
      },
      hideModelChange() {
          if(!this.modelcode) {
              this.$alert("请选择一个模板进行隐藏！");
              this.hidemodelflag = "0";
              return;
          }
          let model = this.modelOption.find((item) => item.modelcode == this.modelcode);
          if(model && model.macaddress != "All") {
              this.$alert("该模板不是全局模板，不支持隐藏，可直接删除！");
              this.hidemodelflag = "0";
              return;
          }
          this.$tool.request({
                  url: "ucent/exportcolsetting",
                  method: "post",
                  data: {
                      action: "hidemodel",
                      modelcode: this.modelcode,
                      prgcode: this.PRGNO,
                  },
              }).then((res)=>{
                  if(res.flag == 1){
                      this.$message.success("模板隐藏成功，已从筛选条件中去除!");
                      this.getOptions();
                  } else {
                      this.$message.error("隐藏模板失败："+ res.msg);
                  }
              }).catch((err)=>{
                  console.log(err);
              });
      },
      ShowModelChange() {
          this.$tool.request({
                  url: "ucent/exportcolsetting",
                  method: "post",
                  data: {
                      action: "showallmodel",
                      prgcode: this.PRGNO,
                  },
              }).then((res)=>{
                  if(res.flag == 1){
                      this.$message.success("全部模板加载成功，隐藏模板已释放!");
                      this.getOptions();
                  } else {
                      this.$message.error("释放隐藏模板失败："+ res.msg);
                  }
              }).catch((err)=>{
                  console.log(err);
              });
      },
      ModifyModel() {
          if(!this.modelcode) {
              this.$alert("请选择一个模板后再进行修改！");
              return;
          }
          this.utype = "2";
          this.modelinfo =  XE.clone(this.modelOption.find((item) => item.modelcode == this.modelcode),true);
          this.overallModel = this.modelinfo.macaddress == "All" ? "1" : "0";
          console.log(this.overallModel);
          this.setExportColumn();
          this.modelVisible = true;
      },
      modChange(code) {
          this.modelcode = code;
          if(code && this.modelOption && this.modelOption.length > 0){
              var model = this.modelOption.find((item) => item.modelcode == code);
              this.exportColTableData = this.colStrToList(model.columnlist);
          } else {
              this.exportColTableData = [];
          }
      },
      AddModel() {
          this.utype = "1";
          this.modelinfo = {
              modelname: "",
          };
          this.overallModel = "0";
          this.setExportColumn();
          this.modelVisible = true;
      },
      DelModel() {
          if(this.modelcode) {
              let model = this.modelOption.find((item) => item.modelcode == this.modelcode);
              if(model) {
                  this.message = model.modelname;
                  this.deldialogVisible = true;
              }
          } else {
              this.$alert("请选择要删除的模板！");
          }
      },
      SubmitDel() {
          this.deldialogVisible = false;
          this.utype = "3";
          this.modelinfo.modelcode = this.modelcode;
          this.SaveModel(2);
      },
      SaveModel(type) {
          if(this.utype != "3") {
              if(!this.modelinfo.modelname) {
                  this.$alert("请输入模板名称！");
                  this.$refs.modelname.focus();
                  return;
              }
          }
          // 这里要再取下最新的然后转成字符，因为可能设置了导出列名
          if(type == 1) {
              this.modelinfo.columnlist = this.colListToStr(this.rightTableData);
          }
          return new Promise((s, f) => {
              this.$tool.request({
                      url: "ucent/exportcolsetting",
                      method: "post",
                      data: {
                          action: "saveexportcol",
                          utype: this.utype,
                          exportcolinfo: this.modelinfo,
                          isall: this.overallModel,
                          prgcode: this.PRGNO,
                      },
                  }).then((res)=>{
                      if(res.flag == 1){
                          this.$message.success(this.utype == "3" ? "删除成功！":"保存成功!");
                          this.modelVisible = false;
                          this.getOptions();
                          s();
                      } else {
                          this.$message.error((this.utype == "3" ? "删除失败：":"保存失败：")+ res.msg);
                          f();
                      }
                  }).catch((err)=>{
                      console.log(err);
                      f();
                  });
          });
      },
      CancelModel() {
          this.modelVisible = false;
      },
      setExportColumn() {
          // 修改并且已经设置过导出列
          if(this.modelinfo.modelcode && this.modelinfo.columnlist) {
              this.rightTableData = this.colStrToList(this.modelinfo.columnlist);
              var allColumnList = [];
              this.allTableCol.forEach(element => {
                  if (element.property) {
                      let rightcol = this.rightTableData.find(item => item.property == element.property);
                      if(!rightcol){
                          allColumnList.push({
                              title: element.title,
                              property: element.property
                          });
                      }
                  }
              });
              this.leftTableData = allColumnList;
          } else { // 新增或者还未设置导出列
              var allColumnList = [];
              this.allTableCol.forEach(element => {
                  if (element.property) {
                      allColumnList.push({
                          title: element.title,
                          property: element.property
                      });
                  }
              });
              this.rightTableData = [];
              this.leftTableData = allColumnList;
          }
      },
      // setExportColumn() {
      //     console.log(this.excolPro)
      //     var leftlocalStorage = "";
      //     var rightlocalStorage = "";
      //     if (this.excolPro == "lis340") { //暂时处理 LIS340 缓存名字不通用问题
      //         leftlocalStorage = JSON.parse(window.localStorage.getItem("noexportColumn"));
      //         rightlocalStorage = JSON.parse(window.localStorage.getItem("exportColumn"));
      //         if (rightlocalStorage && rightlocalStorage.length > 0) {
      //             window.localStorage.setItem(this.excolPro + "noExCol", JSON.stringify(leftlocalStorage));
      //             window.localStorage.setItem(this.excolPro + "exCol", JSON.stringify(rightlocalStorage));
      //             window.localStorage.removeItem("noexportColumn");
      //             window.localStorage.removeItem("exportColumn");
      //         } else {
      //             leftlocalStorage = JSON.parse(window.localStorage.getItem(this.excolPro + "noExCol"));
      //             rightlocalStorage = JSON.parse(window.localStorage.getItem(this.excolPro + "exCol"));
      //         }
      //     } else {
      //         leftlocalStorage = JSON.parse(window.localStorage.getItem(this.excolPro + "noExCol"));
      //         rightlocalStorage = JSON.parse(window.localStorage.getItem(this.excolPro + "exCol"));
      //     }
      //     if (rightlocalStorage && rightlocalStorage.length > 0) {
      //         this.rightTableData = rightlocalStorage;
      //         this.leftTableData = leftlocalStorage;
      //     } else {
      //         var allColumnList = [];
      //         this.allTableCol.forEach(element => {
      //             if (element.property) {
      //                 allColumnList.push({
      //                     title: element.title,
      //                     property: element.property
      //                 });
      //             }
      //         });
      //         this.rightTableData = [];
      //         this.leftTableData = allColumnList;
      //     }
      // },
      ListNoSelectEvent() {
          var delrow = this.$refs.ListxTableRight.getCurrentRow();
          if (delrow) {
              var alld = this.$refs.ListxTableRight.getTableData().fullData;
              var rowindex = alld.indexOf(delrow);
              this.rightTableData.splice(rowindex, 1);
              this.modelinfo.columnlist = this.colListToStr(this.rightTableData);
              this.leftTableData.push(delrow);
              let havedata = this.rightTableData;
              if (havedata.length > 0) {
                  if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                  let selectrow = havedata[rowindex];
                  this.$refs.ListxTableRight.setCurrentRow(selectrow);
              } else {
                  this.$refs.ListxTableRight.setCurrentRow(null);
              }
          }
      },
      ListSelectEvent() {
          var addrow = this.$refs.ListxTableLeft.getCurrentRow();
          if (addrow) {
              var alld = this.$refs.ListxTableLeft.getTableData().fullData;
              var rowindex = alld.indexOf(addrow);
              this.leftTableData.splice(rowindex, 1);
              this.rightTableData.push(addrow);
              this.modelinfo.columnlist = this.colListToStr(this.rightTableData);
              let havedata = this.leftTableData;
              if (havedata.length > 0) {
                  if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                  let selectrow = havedata[rowindex];
                  this.$refs.ListxTableLeft.setCurrentRow(selectrow);
              } else {
                  this.$refs.ListxTableLeft.setCurrentRow(null);
              }
          }
      },
      ListAllSelect() { //全选 右移
          let sdata = this.$refs.ListxTableLeft.getTableData().fullData;
          if (sdata.length > 0) {
              sdata.forEach(item => {
                  let delrow = item;
                  this.$refs.ListxTableLeft.remove(delrow);
                  this.$refs.ListxTableRight.insertAt(delrow, -1);
                  let Rlen = 0;
                  if (this.rightTableData == null) {
                      this.rightTableData = [];
                  } else {
                      Rlen = this.rightTableData.length;
                  }
                  this.rightTableData.splice(Rlen, 0, delrow);
                  this.modelinfo.columnlist = this.colListToStr(this.rightTableData);
              });
              this.leftTableData = [];
          }
      },
      ListAllNoSelect() { //全不选 左移
          let sdata = this.$refs.ListxTableRight.getTableData().fullData;
          if (sdata.length > 0) {
              sdata.forEach(item => {
                  let delrow = item;
                  this.$refs.ListxTableRight.remove(delrow);
                  this.$refs.ListxTableLeft.insertAt(delrow, -1);
                  this.leftTableData.splice(this.leftTableData.length, 0, delrow);
              });
              this.rightTableData = [];
              this.modelinfo.columnlist = this.colListToStr(this.rightTableData);
          }
      },
      dialogVisibleSave() {
          if(this.modelcode && this.exportColTableData.length > 0){
              window.localStorage.setItem(this.excolPro + "exportModel", this.modelcode);
              window.localStorage.setItem(this.excolPro + "exportCol", JSON.stringify(this.exportColTableData));
              this.$message.success("导出模板设置成功！");
              this.$emit("change");
          } else {
              this.$confirm("您确定要放弃设置导出列模板用页面表单导出吗？", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  focusCancelButton: true,
                  type: "warning"
              }).then(() => {
                  window.localStorage.removeItem(this.excolPro + "exportModel");
                  window.localStorage.removeItem(this.excolPro + "exportCol");
                  this.$emit("change");
                  this.$message.success("导出列模板缓存清除成功！");
              }).catch(() => {});
          }
      },
      // dialogVisibleSave() {
      //     if (this.rightTableData.length > 0) {
      //         window.localStorage.setItem(this.excolPro + "noExCol", JSON.stringify(this.leftTableData));
      //         window.localStorage.setItem(this.excolPro + "exCol", JSON.stringify(this.rightTableData));
      //     } else {
      //         window.localStorage.removeItem(this.excolPro + "noExCol");
      //         window.localStorage.removeItem(this.excolPro + "exCol");
      //     }
      //     this.$emit("change");
      // },
  },
}
</script>

<style scoped>
.excol-content {
  display: flex;
  height: 400px;
  width: 100%;
}
.col-table {
  width: 350px;
  height: 100%;
}
.col-arrow {
  width: 60px;
  text-align: center;
  margin: auto;
}
.col-arrow div {
  margin: 15px 0;
}
.excol-btn {
  text-align: right;
  margin-top: 10px;
}
</style>